package com.qf.pojo;

import com.qf.vo.MsgResult;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ShopCart {
    private Map<Integer ,ShopItem> cart=new HashMap();

    public Map<Integer, ShopItem> getCart() {
        return cart;
    }

    public void setCart(Map<Integer, ShopItem> cart) {
        this.cart = cart;
    }

    public Collection<ShopItem> show() {
        return cart.values();//获得map所有值的集合
    }

    //提交订单之前预览提交的明细
    public MsgResult<ShopItem>  show(String[] gids) {
        Collection<ShopItem> shopItems=new ArrayList<ShopItem>();
        MsgResult<ShopItem> msg=new MsgResult();
        float total=0;
        for(String gid:gids){
            Integer id=Integer.valueOf(gid);
            ShopItem item= this.cart.get(id);
            shopItems.add(item);
            total+=item.getNum()*item.getGoods().getPrice();//计算总价
        }
        msg.setItemList(shopItems);
        msg.setTotal(total);
        return msg;//
    }

    //会话里面添加商品
    public int add(Goods goods){
        ShopItem shopItem=new ShopItem();
        if(cart.containsKey(goods.getId())){
            shopItem=cart.get(goods.getId());
            shopItem.setNum(shopItem.getNum()+1);
            return 1;
        }else{
            shopItem.setGoods(goods);
            cart.put(goods.getId(),shopItem);
            return 1;
        }
    }

    //登录时恢复购物车
    public int add(Integer num,Goods goods) {
        ShopItem shopItem=new ShopItem(num,goods);
        this.cart.put(goods.getId(),shopItem);
        return  1;
    }





    public int updateNum(int gid,int flag){
        ShopItem shopItem=cart.get(gid);
        if (flag==-2){
            if (shopItem.getNum()<=1){
                return 1;
            }else {
                shopItem.setNum(shopItem.getNum()-1);
            }
        }else if(flag==-1){
            shopItem.setNum(shopItem.getNum()+1);
        }else {
            shopItem.setNum(flag);
        }
        return shopItem.getNum();
    }

    public ShopItem deleteOne(Integer gid){
        if(gid!=null&&this.cart!=null){
            return cart.remove(gid);
        }
        return  null;
    }

    public void deleteOne(String[] gidS){
        for (String gid:gidS){
            int goodsid=Integer.valueOf(gid);
            this.cart.remove(goodsid);
        }
    }

    @Override
    public String toString() {
        return "购物车{" +
                "项目" + cart.toString() +
                '}';
    }


}
